package com.aimosheng.main.views;

import android.content.Context;
import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aimosheng.common.CommonAppConfig;
import com.aimosheng.common.bean.UserBean;
import com.aimosheng.common.event.FollowEvent;
import com.aimosheng.common.http.HttpCallback;
import com.aimosheng.common.utils.ClickUtil;
import com.aimosheng.common.utils.DialogUitl;
import com.aimosheng.common.utils.SpUtil;
import com.aimosheng.common.utils.ToastUtil;
import com.aimosheng.common.utils.WordUtil;
import com.aimosheng.im.activity.ChatRoomActivity;
import com.aimosheng.im.activity.SystemMessageActivity;
import com.aimosheng.im.adapter.ImListAdapter;
import com.aimosheng.im.bean.ImUserBean;
import com.aimosheng.im.bean.SystemMessageBean;
import com.aimosheng.im.event.ImMessagePromptEvent;
import com.aimosheng.im.event.ImRemoveAllMsgEvent;
import com.aimosheng.im.event.ImUserMsgEvent;
import com.aimosheng.im.event.SystemMsgEvent;
import com.aimosheng.im.http.ImHttpConsts;
import com.aimosheng.im.http.ImHttpUtil;
import com.aimosheng.im.utils.ImMessageUtil;
import com.aimosheng.main.R;
import com.aimosheng.main.activity.SubcribeAncActivity;
import com.aimosheng.main.activity.SubcribeAudActivity;
import com.aimosheng.one.http.OneHttpConsts;
import com.aimosheng.one.http.OneHttpUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.List;

/**
 * Created by cxf on 2019/4/1.
 */

public class MainMessageMsgViewHolder extends AbsMainViewHolder implements View.OnClickListener, ImListAdapter.ActionListener {

    private View mBtnSystemMsg;
    private RecyclerView mRecyclerView;
    private ImListAdapter mAdapter;
    private View mSystemMsgRedPoint;//系统消息的红点
    private TextView mSystemMsgContent;
    private TextView mSystemTime;
    private TextView mSubcribMsg;
    private HttpCallback mSystemMsgCallback;

    public MainMessageMsgViewHolder(Context context, ViewGroup parentView) {
        super(context, parentView);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_main_msg_msg;
    }

    @Override
    public void init() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mAdapter = new ImListAdapter(mContext);
        mAdapter.setActionListener(this);
        mRecyclerView.setAdapter(mAdapter);
        View headView = mAdapter.getHeadView();
        mBtnSystemMsg = headView.findViewById(R.id.btn_system_msg);
        mBtnSystemMsg.setOnClickListener(this);
        mSubcribMsg = headView.findViewById(R.id.msg_appointment);
        headView.findViewById(R.id.btn_appointment).setOnClickListener(this);
        mSystemMsgRedPoint = headView.findViewById(R.id.red_point);
        mSystemMsgContent = headView.findViewById(R.id.msg);
        mSystemTime = headView.findViewById(R.id.time);
        mSystemMsgCallback = new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    SystemMessageBean bean = JSON.parseObject(info[0], SystemMessageBean.class);
                    if (mSystemMsgContent != null) {
                        mSystemMsgContent.setText(bean.getContent());
                    }
                    if (mSystemTime != null) {
                        mSystemTime.setText(bean.getAddtime());
                    }
                    if (SpUtil.getInstance().getBooleanValue(SpUtil.HAS_SYSTEM_MSG)) {
                        if (mSystemMsgRedPoint != null && mSystemMsgRedPoint.getVisibility() != View.VISIBLE) {
                            mSystemMsgRedPoint.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        };
        EventBus.getDefault().register(this);
    }


    @Override
    public void loadData() {
        getSystemMessageList();
        OneHttpUtil.getSubscribeNums(new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    if (mSubcribMsg != null) {
                        JSONObject obj = JSON.parseObject(info[0]);
                        if (obj != null) {
                            mSubcribMsg.setText(String.format(WordUtil.getString(R.string.chat_subcribe_count), obj.getString("nums")));
                        }
                    }
                }
            }
        });
        String uids = ImMessageUtil.getInstance().getConversationUids();
        if (!TextUtils.isEmpty(uids)) {
            ImHttpUtil.getImUserInfo(uids, new HttpCallback() {
                @Override
                public void onSuccess(int code, String msg, String[] info) {
                    if (code == 0) {
                        List<ImUserBean> list = JSON.parseArray(Arrays.toString(info), ImUserBean.class);
                        list = ImMessageUtil.getInstance().getLastMsgInfoList(list);
                        if (mRecyclerView != null && mAdapter != null) {
                            mAdapter.setList(list);
                        }
                    }
                }
            });
        }

    }


    /**
     * 获取系统消息
     */
    private void getSystemMessageList() {
        ImHttpUtil.getSystemMessageList(1, mSystemMsgCallback);
    }

    @Override
    public void onClick(View v) {
        if (!ClickUtil.canClick()) {
            return;
        }
        int i = v.getId();
        if (i == R.id.btn_system_msg) {
            forwardSystemMessage();
        } else if (i == R.id.btn_appointment) {
            forwardSubcribe();
        }
    }

    /**
     * 前往预约
     */
    private void forwardSubcribe() {
        UserBean u = CommonAppConfig.getInstance().getUserBean();
        if (u == null) {
            return;
        }
        if (u.hasAuth()) {
            mContext.startActivity(new Intent(mContext, SubcribeAncActivity.class));
        } else {
            mContext.startActivity(new Intent(mContext, SubcribeAudActivity.class));
        }
    }

    /**
     * 前往系统消息
     */
    private void forwardSystemMessage() {
        SpUtil.getInstance().setBooleanValue(SpUtil.HAS_SYSTEM_MSG, false);
        if (mSystemMsgRedPoint != null && mSystemMsgRedPoint.getVisibility() == View.VISIBLE) {
            mSystemMsgRedPoint.setVisibility(View.INVISIBLE);
        }
        SystemMessageActivity.forward(mContext);
    }

    @Override
    public void onItemClick(ImUserBean bean) {
        if (bean != null) {
            ImMessageUtil.getInstance().markAllMessagesAsRead(bean.getId(), true);
            //跳转聊天页面
            ChatRoomActivity.forward(mContext, bean, bean.isFollowing(), bean.isBlacking(), bean.getAuth() == 1, false);
        }
    }

    @Override
    public void onItemDelete(ImUserBean bean, int size) {
        ImMessageUtil.getInstance().removeConversation(bean.getId());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFollowEvent(FollowEvent e) {
        if (e != null) {
            if (mAdapter != null) {
                mAdapter.setFollow(e.getToUid(), e.getIsAttention());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSystemMsgEvent(SystemMsgEvent e) {
        getSystemMessageList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImUserMsgEvent(final ImUserMsgEvent e) {
        if (e != null && mRecyclerView != null && mAdapter != null) {
            int position = mAdapter.getPosition(e.getUid());
            if (position < 0) {
                ImHttpUtil.getImUserInfo(e.getUid(), new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String[] info) {
                        if (code == 0 && info.length > 0) {
                            ImUserBean bean = JSON.parseObject(info[0], ImUserBean.class);
                            bean.setLastMessage(e.getLastMessage());
                            bean.setUnReadCount(e.getUnReadCount());
                            bean.setLastTime(e.getLastTime());
                            bean.setLastTimeStamp(e.getLastTimeStamp());
                            mAdapter.insertItem(bean);
                        }
                    }
                });
            } else {
                mAdapter.updateItem(e.getLastMessage(), e.getLastTime(), e.getLastTimeStamp(), e.getUnReadCount(), position);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImRevokeMsgEvent(final ImMessagePromptEvent e) {
        if (e != null && mRecyclerView != null && mAdapter != null) {
            int position = mAdapter.getPosition(e.getToUid());
            String msg = e.isSelf() ? WordUtil.getString(R.string.chat_msg_prompt_0) :
                    WordUtil.getString(R.string.chat_msg_prompt_1);
            mAdapter.updateItemNum(ImMessageUtil.getInstance().getUnReadMsgCount(e.getToUid()),
                    msg,
                    position);
        }
//        ImMessageUtil.getInstance().refreshAllUnReadMsgCount();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onImRemoveAllMsgEvent(ImRemoveAllMsgEvent e) {
        if (mAdapter != null) {
            mAdapter.removeItem(e.getToUid());
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        ImHttpUtil.cancel(ImHttpConsts.GET_SYSTEM_MESSAGE_LIST);
        ImHttpUtil.cancel(ImHttpConsts.GET_IM_USER_INFO);
        OneHttpUtil.cancel(OneHttpConsts.GET_SUBSCRIBE_NUMS);
        super.onDestroy();
    }

    /**
     * 忽略未读
     */
    public void ignoreUnReadCount() {
        String unReadCount = ImMessageUtil.getInstance().getAllUnReadMsgCount();
        boolean hasSystemMsg = SpUtil.getInstance().getBooleanValue(SpUtil.HAS_SYSTEM_MSG);
        if ("0".equals(unReadCount) && !hasSystemMsg) {
            DialogUitl.showSimpleTipDialogDark(mContext, null, WordUtil.getString(R.string.im_msg_ignore_unread_3));
            return;
        }
        SpUtil.getInstance().setBooleanValue(SpUtil.HAS_SYSTEM_MSG, false);
        if (mSystemMsgRedPoint != null && mSystemMsgRedPoint.getVisibility() == View.VISIBLE) {
            mSystemMsgRedPoint.setVisibility(View.INVISIBLE);
        }
        ImMessageUtil.getInstance().markAllConversationAsRead();
        if (mAdapter != null) {
            mAdapter.resetAllUnReadCount();
        }
        ToastUtil.show(R.string.im_msg_ignore_unread_2);
    }
}
